const WebSocket = require('ws')
const { accessLog, errorLog } = require('./logger.js')

// 使用Map来存储配对关系
const unityClients = new Map() // { pairKey: WebSocket }
const webClients = new Map()   // { pairKey: WebSocket }

module.exports = (server) => {
  const wss = new WebSocket.Server({ server })
  wss.on('connection', (ws) => {
    accessLog('New client connected')
    let pairKey = null
    let clientType = null

    // 消息处理
    ws.on('message', (message) => {
      try {
        const data = JSON.parse(message)

        // 配对处理
        if (data.type && data.pairKey) {
          if (data.type === 'Unity') {
            if (!unityClients.has(data.pairKey)) {
              pairKey = data.pairKey
              clientType = 'Unity'
              unityClients.set(pairKey, ws)
              accessLog(`Unity client paired: ${pairKey}`)
            }
          } else if (data.type === 'Web') {
            if (!webClients.has(data.pairKey)) {
              pairKey = data.pairKey
              clientType = 'Web'
              webClients.set(pairKey, ws)
              accessLog(`Web client paired: ${pairKey}`)
            }
          }
      }

      // 消息转发逻辑
      if (clientType === 'Unity') {
        const webClient = webClients.get(pairKey)
        if (webClient?.readyState === WebSocket.OPEN) {
          webClient.send(data.data)
        }
      } else if (clientType === 'Web') {
        const unityClient = unityClients.get(pairKey)
        if (unityClient?.readyState === WebSocket.OPEN) {
          unityClient.send(data.data)
        }
      }
    }
  catch
    (error)
    {
      errorLog('Message processing error:', error)
    }
  })

  // 连接关闭处理
  ws.on('close', () => {
    accessLog('Client disconnected')
    if (pairKey) {
      clientType === 'Unity'
        ? unityClients.delete(pairKey)
        : webClients.delete(pairKey)
    }
  })

  // 错误处理
  ws.on('error', (error) => {
    console.error('WebSocket error:', error)
  })
}
)
}
